package com.yy.QSManage.api;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.yy.QSManage.common.Result;
import com.yy.QSManage.model.entity.FaSysMenu;
import com.yy.QSManage.model.entity.FaSysMenuGrid;
import com.yy.QSManage.model.validatio.Create;
import com.yy.QSManage.model.validatio.Update;
import com.yy.QSManage.service.FaSysMenuGridService;
import com.yy.QSManage.service.FaSysMenuService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/FaSysMenuApi")
@Api(tags = "菜单")
public class FaSysMenuApi extends BaseApi<FaSysMenu>{

    @Autowired
    FaSysMenuService menuService;

    @Autowired
    FaSysMenuGridService menuGriService;

    @Override
    public Result<Boolean> add(@RequestBody @Validated(Create.class) FaSysMenu query) {
        List<FaSysMenu> faSysMenus = menuService.listByParam(FaSysMenu::getPid, query.getPid());
        if(!faSysMenus.isEmpty()){
            // 排序
            Collections.sort(faSysMenus);
            query.setSort(faSysMenus.get(0).getSort()+1);
        }else {
            query.setSort(1);
        }
        query.setType("user");
        String uuid = IdUtil.fastSimpleUUID();
        // 生成菜单id
        query.setId(uuid);
        // 添加关联网格
        if(Objects.nonNull(query.getGrids()) && query.getGrids().contains("[")){
            JSONArray grids = JSONUtil.parseArray(query.getGrids());
            if(grids.isEmpty()){
                List<FaSysMenuGrid> faSysMenuGrises = new ArrayList<>();
                for (Object gridId : grids) {
                    FaSysMenuGrid faSysMenuGrid = new FaSysMenuGrid();
                    faSysMenuGrid.setGridId(gridId.toString())
                            .setMenuId(query.getId());
                    faSysMenuGrises.add(faSysMenuGrid);
                }
                menuGriService.saveBatch(faSysMenuGrises);
            }
        }else{
            FaSysMenuGrid faSysMenuGrid = new FaSysMenuGrid();
            faSysMenuGrid.setGridId(query.getGrids())
                    .setMenuId(query.getId());
            menuGriService.save(faSysMenuGrid);
        }
        return super.add(query);
    }

    @Override
    public Result<Boolean> edit(@RequestBody @Validated(Update.class) FaSysMenu query) {
        JSONArray gridsJosn;
        List<FaSysMenuGrid> faSysMenuGrises = List.of();
        List<String> grids = List.of();
        try {
            gridsJosn = JSONUtil.parseArray(query.getGrids());
            grids = gridsJosn.toList(String.class);
            faSysMenuGrises = menuGriService.listByParam(FaSysMenuGrid::getMenuId, query.getId());
            List<String> gridIds = faSysMenuGrises.stream().map(FaSysMenuGrid::getGridId).collect(Collectors.toList());
            // 新增网格关联
            List<String> addGridIds = grids.stream().filter(gridId -> !gridIds.contains(gridId)).collect(Collectors.toList());
            List<FaSysMenuGrid> addMenuGris = new ArrayList<>();
            for (String addGridId : addGridIds) {
                FaSysMenuGrid faSysMenuGrid = new FaSysMenuGrid();
                faSysMenuGrid.setGridId(addGridId)
                        .setMenuId(query.getId());
                addMenuGris.add(faSysMenuGrid);
            }
            menuGriService.saveBatch(addMenuGris);
        } catch (Exception e) {
            log.info("菜单未关联网格");
        }
        // 删除网格关联
        if(!faSysMenuGrises.isEmpty()){
            List<String> finalGrids = grids;
            List<String> delMenuGridIds = faSysMenuGrises.stream().filter(menuGri -> !finalGrids.contains(menuGri.getGridId())).map(FaSysMenuGrid::getId).collect(Collectors.toList());
            menuGriService.removeByIds(delMenuGridIds);
        }
        return super.edit(query);
    }

    @Override
    public Result<Boolean> del(@PathVariable String id) {
        // 判断删除的菜单是否存在子菜单，一并删除
        List<FaSysMenu> faSysMenus = menuService.listByParam(FaSysMenu::getPid, id);
        if(Objects.nonNull(faSysMenus) && !faSysMenus.isEmpty()){
            menuService.removeByParam(FaSysMenu::getPid, id);
        }
        return super.del(id);
    }
}
